using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace CodeNameGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private Texture2D bg_stars;
        private MainPlayer mainPlayer;
        private MainPlayer mainVillain;
        private KeyboardState oldState;


        private Matrix world = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldVillain = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix view = Matrix.CreateLookAt(new Vector3(0, 0, 30), new Vector3(0, 0, 0), Vector3.UnitY);
        private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), Constants.SCREEN_WIDTH / Constants.SCREEN_HEIGHT, 1.0f, 100f);

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.IsMouseVisible = true;
            graphics.PreferredBackBufferWidth = Constants.SCREEN_WIDTH;
            graphics.PreferredBackBufferHeight = Constants.SCREEN_HEIGHT;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            mainPlayer = new MainPlayer();
            mainVillain = new MainPlayer();

            mainPlayer.m_position = new Vector3(-10, 0, 0);
            mainVillain.m_position = new Vector3(0, 0, 0);
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            bg_stars = Content.Load<Texture2D>("Background/stars");

            mainPlayer.LoadModel(this.Content, "3DModels/BeachBall");
            mainPlayer.LoadTexture(this.Content, "3DModels/BeachBallTexture");
            
            mainVillain.LoadModel(this.Content, "3DModels/BeachBall");
            mainVillain.LoadTexture(this.Content, "3DModels/BeachBallTexture");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            mainVillain.m_angle += 0.03f;
            mainPlayer.m_angle += 0.03f;
            world = Matrix.CreateRotationY(mainPlayer.m_angle) * Matrix.CreateTranslation(mainPlayer.m_position);
            worldVillain = Matrix.CreateRotationY(mainPlayer.m_angle) * Matrix.CreateTranslation(mainVillain.m_position);

            Matrix heroMatrix = Matrix.CreateTranslation(mainPlayer.m_position);
            Matrix villainMatrix = Matrix.CreateTranslation(mainVillain.m_position);

            KeyboardState newState = Keyboard.GetState();
            foreach (var pressedKey in newState.GetPressedKeys())
            {
                switch (pressedKey)
                {
                    case Keys.Up:
                        if(!IsCollision(mainPlayer.model, heroMatrix, mainVillain.model, villainMatrix))
                        {
                            mainPlayer.m_position += new Vector3(0, 1, 0);
                        }
                        else
                        {
                            mainPlayer.m_position -= new Vector3(0, 1, 0);
                        }
                        break;
                    case Keys.Down:
                        if (!IsCollision(mainPlayer.model, heroMatrix, mainVillain.model, villainMatrix))
                        {
                            mainPlayer.m_position -= new Vector3(0, 1, 0);
                        }
                        else
                        {
                            mainPlayer.m_position += new Vector3(0, 1, 0);
                        }
                        break;
                    case Keys.Right:
                        if(!IsCollision(mainPlayer.model, heroMatrix, mainVillain.model, villainMatrix))
                        {
                            mainPlayer.m_position += new Vector3(1, 0, 0);
                        }
                        else
                        {
                            mainPlayer.m_position -= new Vector3(1, 0, 0);
                        }
                        break;
                    case Keys.Left:
                        if(!IsCollision(mainPlayer.model, heroMatrix, mainVillain.model, villainMatrix))
                        {
                            mainPlayer.m_position -= new Vector3(1, 0, 0);
                        }
                        else
                        {
                            mainPlayer.m_position += new Vector3(1, 0, 0);
                        }
                        break;
                }
            }
            oldState = newState;


            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            spriteBatch.Draw(bg_stars, new Rectangle(0, 0, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT), Color.White);
            spriteBatch.End();
            mainPlayer.DrawPlayer(world, view, projection);
            mainVillain.DrawPlayer(worldVillain, view, projection);

            base.Draw(gameTime);
        }

        private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
        {
            for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
            {
                BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
                sphere1 = sphere1.Transform(world1);

                for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
                {
                    BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
                    sphere2 = sphere2.Transform(world2);

                    if (sphere1.Intersects(sphere2))
                        return true;
                }
            }
            return false;
        }
    }
}
